<template>
    <Transition>
        <div class="contain" v-if="flag">
            <div class="card" style="min-width: 900px;">
                <div class="header flex">
                    <div class="goHome flex">
                        <p class="title">新增入库单</p>
                    </div>
                    <div class="flex">
                        <!-- <button class="submit" @click="addHandle"
                            v-loading.fullscreen.lock="fullscreenLoading">提交</button> -->
                        <el-icon size="22" style="margin-right: 37px; cursor: pointer;" @click="closeHandle">
                            <Close />
                        </el-icon>
                    </div>
                </div>
                <div class="main">
                    <h4 style="margin-bottom: 10px;">基本信息</h4>
                    <div class="main_li1">
                        <div class="inputBox inputBox1">
                            <p class="inputName">入库单标题<span>*</span></p>
                            <input type="text" class="myInput" placeholder="请填写入库单标题" v-model="form.title"
                                :disabled="submitFlag">
                        </div>
                        <div class="inputBox inputBox1">
                            <p class="inputName">供应商<span>*</span></p>
                            <input type="text" class="myInput" placeholder="请填写供应商" v-model="form.supplier"
                                :disabled="submitFlag">
                        </div>
                        <div class="inputBox inputBox1">
                            <p class="inputName">备注</p>
                            <input type="text" class="myInput" placeholder="请填写备注" v-model="form.remark"
                                :disabled="submitFlag">
                        </div>
                    </div>
                    <h4 style="margin-bottom: 10px;">入库物资</h4>
                    <div class="main_li1">
                        <div class="inputBox inputBox1">
                            <p class="inputName">物资名称<span>*</span></p>
                            <el-select v-model="form.materialld" placeholder="请选择物资名称" class="select" clearable
                                filterable @change="changeMaterial" @clear="clearMaterial" :disabled="submitFlag">
                                <el-option v-for="item in materialList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </div>
                        <div class="inputBox inputBox1">
                            <p class="inputName">入库数量<span>*</span></p>
                            <input type="number" min="0" class="myInput" :placeholder="unit" v-model="form.quantity"
                                :disabled="submitFlag">
                        </div>
                        <div class="inputBox inputBox1">
                            <p class="inputName">单价<span>*</span></p>
                            <input type="number" min="0" class="myInput" placeholder="请填写单价" v-model="form.price"
                                :disabled="submitFlag">
                        </div>
                        <div class="inputBox inputBox1">
                            <p class="inputName">批次号<span>*</span></p>
                            <input type="text" class="myInput" placeholder="请填写批次号" v-model="form.batchNo"
                                :disabled="submitFlag">
                        </div>

                    </div>
                    <div class="main_li">

                    </div>


                </div>

                <div style="display: flex; align-items: center; justify-content: flex-start; margin-left: 60px;">
                    <div class="applyBtn" @click="addHandleCopy" v-if="!submitFlag">加入入库单</div>
                    <div class="applyBtn" @click="printHandleCopy('仅保存')" v-if="!submitFlag"
                        v-loading.fullscreen.lock="fullscreenLoading" style="margin-left: 30px;">仅保存</div>
                    <div class="applyBtn" @click="printHandleCopy('保存并打印')" v-if="!submitFlag"
                        v-loading.fullscreen.lock="fullscreenLoading" style="margin-left: 30px;">保存并打印</div>
                    <div class="applyBtn" v-if="submitFlag" @click="printHandle"
                        v-loading.fullscreen.lock="fullscreenLoading">打印</div>
                </div>


                <div class="printMain" id="printMain" ref="print">
                    <div style="padding-bottom: 15px;">
                        <h3 class="printTitle">{{ schoolName }}卫材外购入库单</h3>
                    </div>
                    <div class="table_box">
                        <el-table :data="printList1" border style="width: 100%;font-size: 14px;" class="custom-table"
                            :header-cell-style="{ 'background': '#F6F6FE', 'color': '#5B686D' }" size="small"
                            :cell-style="{ 'color': '#5B686D' }">
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="materialName" label="材料信息" min-width="200" />
                            <el-table-column prop="categoriesName" label="材料类别" />
                            <el-table-column prop="specification" label="规格" />
                            <el-table-column prop="unit" label="单位" />
                            <el-table-column prop="quantity" label="数量" />
                            <el-table-column prop="price" label="采购价">
                                <template #default="scope">
                                    <span>{{ scope.row.price.toFixed(5) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="采购价金额">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="售价">
                                <template #default="scope">
                                    <span>{{ scope.row.price.toFixed(5) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="售价金额">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" width="100px" v-if="!submitFlag">
                                <template #default="scope">
                                    <el-button type="danger" style="padding: 0 10px;"
                                        @click="deleteHandle(scope.row, scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="flex footer">
                            <p>&emsp;摘要</p>
                            <p>&emsp;总金额：{{ allMoney }} 元</p>
                            <p>&emsp;填制人：{{ user.name }}</p>
                            <p>&emsp;填制日期：{{ nowDate }}</p>
                        </div>
                    </div>
                </div>



            </div>
        </div>
    </Transition>
</template>

<script>
import { httpService } from "@/utils/httpService";
import Icon from '@/components/Icon.vue';
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElMessage, ElForm, ElLoading } from "element-plus";
import { formatTime, formatTime1 } from "@/utils/dateFormat";
import { getCurrentInstance } from "vue";

export default {
    name: "leftMenu",
    components: { Icon, ArrowLeft, ElMessage, ElForm, ElLoading, Close },
    data() {
        return {
            flag: false,
            form: {
                materialName: "",
                materialId: "",
                quantity: "",
                batchNo: "",
                supplier: "",
                price: "",
                title: "",
                remark: "",

                categoriesName: "",
                specification: "",
                unit: "",

            },
            printForm: {
                number: "",
                supplier: "",
            },

            formRules: {
                materialld: "请选择物资",
                quantity: "请填写入库数量",
                price: "请填写单价",
                batchNo: "请填写填写批次号",
                supplier: "请填写供应商名称",
            },
            unit: "请填写入库数量",
            materialList: [],
            fullscreenLoading: false,
            user: {},
            nowDate: "",

            submitFlag: false,
            printList: [],
            printList1: [],
            schoolName: "",
            allMoney: 0,
        };
    },
    computed: {
        allMoney() {
            return this.printList1.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        },

    },

    mounted() {
        const instance = getCurrentInstance()
        this.schoolName = instance.appContext.config.globalProperties.$schoolName
        this.nowDate = formatTime(new Date())
        this.user = JSON.parse(sessionStorage.getItem("user"))
    },
    methods: {

        addHandleCopy() {
            if (!this.form.title) {
                ElMessage.error("请填写入库单标题")
            } else if (!this.form.materialld) {
                ElMessage.error("请选择物资")
            } else if (!this.form.quantity) {
                ElMessage.error("请填写入库数量")
            } else if (!this.form.price) {
                ElMessage.error("请填写单价")
            } else if (!this.form.batchNo) {
                ElMessage.error("请填写填写批次号")
            } else if (!this.form.supplier) {
                ElMessage.error("请填写供应商名称")
            } else {
                const obj = {
                    materialName: this.form.materialName,
                    materialId: this.form.materialld,
                    quantity: this.form.quantity,
                    price: this.form.price,
                    batchNo: this.form.batchNo,
                }
                const obj1 = {
                    materialName: this.form.materialName,
                    materialId: this.form.materialld,
                    quantity: this.form.quantity,
                    price: this.form.price,
                    batchNo: this.form.batchNo,
                    supplier: this.form.supplier,
                    categoriesName: this.form.categoriesName,
                    specification: this.form.specification,
                    unit: this.form.unit,

                }

                this.printList.push(obj)
                this.printList1.push(obj1)
                this.clearCopy()
                console.log(this.printList);
            }

        },

        printHandleCopy(str) {
            // this.printHandle()
            if (this.printList.length <= 0) {
                ElMessage.error("入库单为空，请添加物资后点击保存并打印");
                return
            }

            this.fullscreenLoading = true
            let params = new FormData()
            params.append("json", JSON.stringify(this.printList))
            params.append("title", this.form.title)
            params.append("remark", this.form.remark)
            params.append("supplier", this.form.supplier)
            httpService("/javaApi/stockInReceipt/add", params, "post").then((data) => {
                this.fullscreenLoading = false
                if (data.code == 200) {
                    this.submitFlag = true
                    ElMessage.success("入库成功");

                    if (str && str == '保存并打印') {
                        setTimeout(() => {
                            this.printHandle()
                        }, 100)
                    }
                } else {
                    ElMessage.error(data.message ? data.message : data.object ? data.object : "入库失败");
                }
            });

        },


        clearCopy() {
            this.form.materialld = ""
            this.form.materialName = ""
            this.form.quantity = ""
            this.form.batchNo = ""
            this.form.price = ""
            this.unit = `请填写入库数量`
        },
        closeHandle() {
            this.flag = false
            this.materialName = ""
            this.materialld = ""
            this.quantity = ""
            this.batchNo = ""
            this.supplier = ""
            this.price = ""
            this.title = ""
            this.remark = ""
            this.printList = []
            this.nowDate = ""
            this.submitFlag = false

            this.form.title = ""
            this.form.supplier = ""
            this.form.remark = ""
            this.printForm.number = ""

            this.printList1 = []
            this.$parent.getMylist()

        },

        printHandle() {
            this.nowDate = formatTime1(new Date())

            const itemsPerPage = 10; // 每页最多打印的条目数
            const totalPages = Math.ceil(this.printList1.length / itemsPerPage); // 总页数

            // 将数据分成每页的组
            const paginatedList = Array.from({ length: totalPages }, (_, i) =>
                this.printList1.slice(i * itemsPerPage, (i + 1) * itemsPerPage)
            );
            let totalSum = 0; // 初始化合计为 0
            const printContent = paginatedList.map((pageItems, pageIndex) => {

                const pageSum = pageItems.reduce((sum, item) => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return sum + itemTotal;
                }, 0);
                totalSum += pageSum;
                return `
            <div class="table-container">
                <p class="pTitle">${this.schoolName}卫材外购入库单</p>
                <div class="table-header">
                    <div>NO.Y${this.printForm.number}</div>  
                </div>
                <div class="table-info">
                    <span>库房: 物资库房</span>
                    <span>第 ${pageIndex + 1} 页/共 ${totalPages} 页</span>
                    <span>供应商: ${this.form.supplier}</span> 
                </div>
                <table>
                    <thead>
                        <tr>
                            <td>材料信息</td>
                            <td>材料类别</td>
                            <td>规格</td>
                            <td>单位</td>
                            <td>数量</td>
                            <td>采购价</td>
                            <td>采购价金额</td>
                            <td>售价</td>
                            <td>售价金额</td>
                        </tr>
                    </thead>
                    <tbody>
                        ${pageItems.map(item => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return ` 
                        <tr>
                            <td>${item.materialName}</td>
                            <td>${item.categoriesName}</td>
                            <td>${item.specification}</td>
                            <td>${item.unit}</td>
                            <td>${item.quantity}</td>
                            <td>${item.price.toFixed(5)}</td>
                            <td>${itemTotal.toFixed(5)}</td>  
                            <td>${item.price.toFixed(5)}</td>
                            <td>${itemTotal.toFixed(5)}</td>  
                        </tr>
                            `;
                }).join('')} 
                        <tr>
                            <td>本页小计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${pageSum.toFixed(5)}</td>
                        </tr>
                        <tr>
                            <td>合&emsp;计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${totalSum.toFixed(5)}</td>
                        </tr> 
                    </tbody>
                </table>
                <div class="table-footer">
                    <div>摘要</div>
                    <div>填制人: ${this.user.name}</div>
                    <div>填制日期: ${this.nowDate}</div> 
                </div>
            </div>
            <div style="page-break-after: always;"></div> <!-- 确保分页 -->
        `;
            }).join('');

            // 创建打印窗口
            const WinPrint = window.open('', '', 'width=800,height=600');
            WinPrint.document.write(`
        <html>
        <head>
            <title>打印</title>
            <style>
                @media print { 
                    @page {
                        margin: 30px 20mm;
                    }
                    body {
                        margin: 0;
                        font-family: Arial, sans-serif;
                    }
                    .table-container {
                        width: 100%;
                        text-align: center;
                        page-break-before: always; /* 强制每个新内容开始时分页 */
                    }
                    .table-container:last-child {
                        page-break-after: auto; /* 最后一页不分页 */
                    }
                    .table-header,
                    .table-info,
                    .table-footer {
                        display: flex;
                        justify-content: space-between; 
                    }
                    .pTitle {
                        font-size: 20px;
                        font-weight: 400;
                        text-align: center;
                    }
                    table {
                        width: 100%;
                        border: 1px solid #000;
                        border-collapse: collapse;
                    }
                    th, td {
                        border: 1px solid #000; 
                        text-align: center;
                    }
                    tr:nth-child(even) {
                        background-color: #f2f2f2; /* 隔行变色 */
                    }
                }
            </style>
        </head>
        <body>
            ${printContent}
        </body>
        </html>
    `);
            WinPrint.document.close();
            WinPrint.print();
            WinPrint.close();
        },





        deleteHandle(data, index) {
            this.printList.splice(index, 1);
            this.printList1.splice(index, 1);
        },
        addHandle() {
            if (!this.form.materialld) {
                ElMessage.error("请选择物资")
            } else if (!this.form.quantity) {
                ElMessage.error("请填写入库数量")
            } else if (!this.form.price) {
                ElMessage.error("请填写单价")
            } else if (!this.form.batchNo) {
                ElMessage.error("请填写填写批次号")
            } else if (!this.form.supplier) {
                ElMessage.error("请填写供应商名称")
            } else {
                this.fullscreenLoading = true
                let params = new FormData()
                params.append("materialName", this.form.materialName)
                params.append("materialId", this.form.materialld)
                params.append("quantity", this.form.quantity)
                params.append("price", this.form.price)
                params.append("batchNo", this.form.batchNo)
                params.append("supplier", this.form.supplier)

                httpService("/javaApi/stockIn/add", params, "post").then((data) => {
                    this.fullscreenLoading = false
                    if (data.code == 200) {
                        ElMessage.success("入库成功");
                        this.clear();
                        this.$parent.getMylist();
                    } else {
                        ElMessage.error("入库失败");
                    }
                });
            }
        },
        changeMaterial(value) {
            const arr = this.materialList.filter(item => item.id == value)
            if (arr.length > 0) {
                this.form.materialName = arr[0].name
                this.form.categoriesName = arr[0].categoriesName
                this.form.specification = arr[0].specification
                this.form.unit = arr[0].unit
                this.unit = `请填写入库数量（单位：${arr[0].unit})`

            }
        },
        clearMaterial() {
            this.unit = `请填写入库数量`
            this.form.materialName = ""
            this.form.categoriesName = ""
            this.form.specification = ""
            this.form.unit = ""

            this.form.quantity = ""
            this.form.price = ""
            this.form.batchNo = ""
        },
        clear() {
            this.flag = false
            this.form.materialld = ""
            this.form.quantity = ""
            this.form.batchNo = ""
            this.form.supplier = ""
            this.unit = `请填写入库数量`
        },
        getMaterialList() {
            //从缓存中获取用户的信息，判断,临时的写法，后续需要修改
            let userInfo  = sessionStorage.getItem('user')
            userInfo = JSON.parse(userInfo);
            let campus = 2;
            if(userInfo&&userInfo.teacherNumber=='240085'){
                campus = 2;
            }else{
                campus = 1;
            }

            httpService("/javaApi/materials/list/1/10000", {campus:campus}, "get").then((data) => {
                if (data.total > 0) {
                    data.list.map(item => item.name = `${item.name} (单位：${item.unit}，规格：${item.specification} )`)
                    this.materialList = data.list
                }
            });
        },
        queryById(id) {
            httpService("/javaApi/baseTeacher/queryById", { id: id }, "get").then((data) => {
                console.log(data);
                if (data) {
                    this.form = data
                }
            });
        },
        getNumberId() {
            httpService("/javaApi/stockInReceipt/list/1/1", {}, "get").then((data) => {
                if (data) {
                    this.printForm.number = data.list[0].receiptCode
                }
            });
        },

    },
}
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    align-items: center;
}

.contain {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.35);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    align-items: flex-start;
    justify-content: center;
}

.card {
    width: 70%;
    height: calc(100vh - 100px);
    background-color: #fff;
    border-radius: 13px;
    margin-top: 50px;
}

.table_box {
    height: calc(100vh - 600px);
    overflow: auto;
}

.header {
    justify-content: space-between;
    height: 65px;
    border-bottom: 1px solid #D6DBE2;
}

.header .title {
    color: #000000;
    font-size: 18px;
    font-weight: bold;
    margin-left: 32px;
}

.submit {
    width: 77px;
    height: 38px;
    background-color: #6F72FF;
    border-radius: 10px;
    border: none;
    margin-right: 32px;
    color: #fff;
    font-size: 15px;
}

.main {
    padding: 10px 60px 0 60px;
    margin: 0 auto 0;
    overflow-y: auto;
}

.main_li {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
}

.main_li1 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 30px;
}

.inputBox1 {
    width: 100% !important;
}

.inputBox {
    width: calc((100% - 90px) / 3);
    /* width: calc((100% - 100px) / 2); */
    margin-bottom: 15px;
    margin-right: 30px;
}

.inputName {
    color: #5B686D;
    font-size: 15px;
    margin-bottom: 5px;
}

.inputName span {
    color: #FF0000;
    font-size: 15px;
    margin-bottom: 5px;
}

.myInput {
    width: calc(100% - 19px);
    height: 42px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    outline: none;
    font-size: 15px;
    color: #000;
    padding-left: 19px;
}

.myInput::placeholder {
    color: #A9B6BB;
}

.myText {
    width: calc(100% - 36px);
    height: 150px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    resize: none;
    outline: none;
    padding: 18px;
    font-size: 15px;
    color: #000;
}

.myText::placeholder {
    color: #A9B6BB;
}


input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* 对于Firefox */
input[type="number"] {
    -moz-appearance: textfield;
}

.select ::v-deep .el-tooltip__trigger {
    width: 100%;
    height: 44px;
    border-radius: 10px;
}

.el-select-dropdown__item {
    padding-left: 15px;
}

::v-deep .el-select {
    --el-color-primary: #D6DBE2;
}



.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}




.applyBtn {
    width: 100px;
    line-height: 35px;
    border-radius: 10px;
    font-size: 15px;
    background-color: #6F72FF;
    color: #fff;
    text-align: center;
    cursor: pointer;
}

.footer {
    justify-content: space-between;
}

.printMain {
    margin: 0 60px;
}
</style>